package com.wangp.mywrite.s_netty.netty.ch1;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @description: TODO
 * @author tooStronger
 * @date 2023/3/17
 */
public class HelloClient {

    public static void main(String[] args) throws InterruptedException {
        // 1. 创建启动器类
        new Bootstrap()
                // 2. 添加eventLoop
                .group(new NioEventLoopGroup())
                // 3. 客户端channel实现
                .channel(NioSocketChannel.class)
                // 4. 添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    // 建立连接后调用
                    @Override
                    protected void initChannel(NioSocketChannel nsc) throws Exception {
                        nsc.pipeline().addLast(new StringEncoder());
                    }
                })
                // 5.连接到服务器
                .connect(new InetSocketAddress("localhost", 8080))
                // 阻塞直到连接建立
                .sync()
                .channel()
                // 6. 向服务器发送数据
                .writeAndFlush("hello world");
    }
}
